﻿using AutoMapper;
using Hsp.WebNovels.Model.Dtos;
using Hsp.WebNovels.Model.Models;
using Hsp.WebNovels.Web.Models;
using Hsp.WebNovels.Web.Utilities;
using HtmlAgilityPack;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections;
using System.Diagnostics;
using System.Text;
using System.Web;

namespace Hsp.WebNovels.Web.Controllers
{
    public class HomeController : BaseController
    {
        #region 控制器初始化

        private readonly IMapper _mapper;
        private readonly NovelsContext _context;
        private readonly ILogger<HomeController> _logger;

        public object Id { get; private set; }

        public HomeController(ILogger<HomeController> logger, NovelsContext context, IMapper mapper) : base(logger, context, mapper)
        {
            this._logger = logger;
            this._mapper = mapper;
            this._context = context;
        }

        #endregion

        /// <summary>
        /// 首页视图--站点管理
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Index()
        {
            //var encoding = "utf-8";
            //var novelUrl = "https://www.73zw8.com/131_131787/";
            //var xpathAddress = "//div[@id=\"list\"]/dl/dd/a";

            ////通过xpath指定页面节点获取节点中对应的内容
            //HtmlDocument ? htmlAddress = await HtmlDocAsync(novelUrl, encoding);
            //if (htmlAddress == null)
            //{
            //    throw new Exception("获取小说地址代码数据为空");
            //}
            //var nodes = htmlAddress.DocumentNode.SelectNodes(xpathAddress);

            //var abc = nodes;

            var chapters = await Db.Queryable<Chapter>()
                        .Where(c => c.NovelId == "EC909066-9BB5-4C0A-A978-73956949905E").ToListAsync();

            var count = chapters.Count();


            //var webSites = await _context.WebSites.ToListAsync();
            await Task.Delay(0);
            return View(new WebSiteViewModel());
        }

        public IActionResult Privacy()
        {
            return View();
        }

        // POST: Home/Delete/5
        [HttpPost, ActionName("Delete")]
        public async Task<IActionResult> DeleteConfirmed(string id)
        {
            using var transaction = await _context.Database.BeginTransactionAsync();

            try
            {
                if (_context.WebSites == null)
                {
                    return Problem("Entity set 'WisdomRecyclingContext.RecyclingSites' is null.");
                }
                var Website = await _context.WebSites.FindAsync(id);
                if (Website != null)
                {
                    _context.WebSites.Remove(Website);
                }

                await _context.SaveChangesAsync();
                await transaction.CommitAsync(); // 事务提交
                return Json(new { success = true, message = "站点删除成功" });
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync(); // 事务回滚
                _logger.LogError($"{nameof(DeleteConfirmed)}：{ex}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 批量删除数据
        /// POST: Home/BatchDelete/5,7
        /// </summary>
        /// <param name="id">数据编号集合</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> BatchDelete(string? id)
        {
            using var transaction = await _context.Database.BeginTransactionAsync();

            try
            {
                if (string.IsNullOrEmpty(id))
                {
                    return Json(new { success = false, Message = "要删除的站点数据主键集合为空！" });
                }
                var idarr = id.Trim().Split(',');
                foreach (var idd in idarr)
                {
                    var Website = await _context.WebSites.FindAsync(int.Parse(idd));
                    if (Website != null) _context.WebSites.Remove(Website);
                }
                await _context.SaveChangesAsync();
                await transaction.CommitAsync(); // 事务提交
                return Json(new { success = true, message = "站点数据删除成功！" });
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync(); // 事务回滚
                _logger.LogError($"{nameof(BatchDelete)}：{ex}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        private bool WebSiteExists(string? id)
        {
            return _context.WebSites.Any(e => e.Id == id);
        }


        #region 站点列表数据视图

        /// <summary>
        /// 站点列表数据视图
        /// GET: Home/TableList
        /// </summary>
        /// <param name="mid">菜单ID</param>
        /// <param name="mapname">菜单路径</param>
        /// <returns></returns>
        public IActionResult TableList(int? mid, string? mapname)
        {
            WebSiteDto dto = new();
            var model = _mapper.Map<WebSiteViewModel>(dto);
            return View(model);
        }

        #endregion 

        #region 站点分页数据查询

        /// <summary>
        /// 站点分页数据查询
        /// GET: Home/PageList
        /// </summary>
        /// <param name="pageNumber">当前页码</param>
        /// <param name="pageSize">分页大小</param>
        /// <param name="title">检索关键词</param>
        /// <returns></returns>
        public JsonResult PageList(int? pageNumber, int? pageSize, string? title, string? startDate, string? endDate)
        {
            try
            {
                #region 参数处理

                var urlDecode = HttpUtility.UrlDecode(title);
                if (urlDecode != null) title = title == null ? "" : urlDecode.Trim();

                string strQry = "";

                if (!string.IsNullOrEmpty(title))
                {
                    //strQry += string.Format(@" AND (w.Title LIKE '%{0}%' OR w.ABCDEF LIKE '%{0}%')", title);
                }
                // 起止日期
                if (!string.IsNullOrEmpty(startDate) && !string.IsNullOrEmpty(endDate))
                {
                    strQry += string.Format(@" AND(unix_timestamp(w.`CreateTime`) between unix_timestamp('{0}') and unix_timestamp(DATE_ADD('{1}', INTERVAL 1 DAY)))", startDate, endDate);
                }
                if (!string.IsNullOrEmpty(startDate) && string.IsNullOrEmpty(endDate))
                {
                    strQry += string.Format(@" AND(unix_timestamp(w.`CreateTime`) > unix_timestamp('{0}'))", startDate, endDate);
                }
                if (string.IsNullOrEmpty(startDate) && !string.IsNullOrEmpty(endDate))
                {
                    strQry += string.Format(@" AND(unix_timestamp(w.`CreateTime`) < unix_timestamp(DATE_ADD('{1}', INTERVAL 1 DAY)))", startDate, endDate);
                }

                #endregion

                #region 分页及页码数据处理处理

                if (!pageNumber.HasValue) pageNumber = 1;
                if (!pageSize.HasValue) pageSize = 10;

                var skip = (pageNumber.Value - 1) * pageSize.Value;

                var min = (pageNumber - 1) * pageSize + 1;
                var max = pageNumber * pageSize;

                #endregion

                var strSql = string.Format(@"
	                ;WITH PageTb AS (
		                SELECT ROW_NUMBER() OVER (ORDER BY CreateTime) RowNumber
			                ,Id,Name,WebUrl,AddressObject,AddressNext,ContentObject,ContentNext,Encoding,UrlCombine,AnnotationType,Valid,CreateTime,UpdateTime
		                FROM dbo.[WebSites] w WHERE (1 = 1) 
		                 {2} 
		                )
	                SELECT * 
	                FROM PageTb a
	                CROSS JOIN (SELECT MAX(RowNumber) AS RecordCount FROM PageTb) AS b 
	                WHERE (a.RowNumber BETWEEN {0} AND {1});
                 ", min, max, strQry);

                var list = Db.Ado.SqlQuery<WebSiteDto>(strSql);
                //_context.Database.SqlQuery<WebSiteDto>(strSql).ToList();

                return Json(new { success = true, total = list?.Count > 0 ? list[0].RecordCount : 0, rows = list });
            }
            catch (Exception ex)
            {
                _logger.LogError($"{nameof(PageList)}：{ex}");
                return Json(new { success = false, total = 0, rows = new List<Hashtable>(), message = ex.Message });
            }
        }

        #endregion

        #region 站点数据保存

        /// <summary>
        /// 站点数据保存
        /// POST: Home/Save
        /// </summary>
        /// <param name="Website">站点</param>
        /// <returns></returns>
        public async Task<IActionResult> Save([FromBody] WebSite Website)
        {
            try
            {
                string flag;
                if (string.IsNullOrEmpty(Website.Id) || !WebSiteExists(Website.Id))
                {
                    flag = "添加";
                    Website.Id = Guid.NewGuid().ToString().ToUpper();
                    Website.CreateTime = DateTime.Now;
                    _context.Add(Website);
                }
                else
                {
                    flag = "修改";
                    Website.UpdateTime = DateTime.Now;
                    _context.Update(Website);
                }

                await _context.SaveChangesAsync();

                return Json(new { success = true, message = $"站点数据{flag}成功!" });

            }
            catch (Exception ex)
            {
                _logger.LogError($"{nameof(Save)}：{ex}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        #endregion









        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}